package com.chen.base.module.mybatis.utils;

import cn.hutool.core.lang.Assert;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.chen.root.enums.DriveEnum;
import com.chen.base.module.mybatis.component.DynamicDataSourceDruidProperty;
import com.chen.base.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @author: ChenJinLong
 * @DATE: 2024/11/15
 **/
@Slf4j
public class DataSourceUtil {

    /** 获取数据源集 */
    public static Map<String, DataSource> getDataSources(){
        return dynamicRoutingDataSource().getDataSources();
    }

    /** 新增数据源 */
    public static void addDataSource(String dsName, String dsType, String url,
                                     String username, String passwd){
        if (getDataSources().containsKey(dsName)){
            log.warn("重复增加动态数据源 -> {}", dsName);
            return;
        }

        DynamicDataSourceDruidProperty druidProperty = SpringContextHolder.getBean(DynamicDataSourceDruidProperty.class);
        DefaultDataSourceCreator dataSourceCreator = SpringContextHolder.getBean(DefaultDataSourceCreator.class);

        DriveEnum driveEnum = DriveEnum.typeMate(dsType);
        Assert.notNull(driveEnum, "不支持的数据源类型!");

        DataSourceProperty dsProperty = new DataSourceProperty();
        dsProperty.setType(DruidDataSource.class);
        dsProperty.setDriverClassName(driveEnum.getDrive());
        dsProperty.setUrl(url);
        dsProperty.setUsername(username);
        dsProperty.setPassword(passwd);
        dsProperty.setDruid(druidProperty.getDruid());

        DataSource dataSource = dataSourceCreator.createDataSource(dsProperty);
        dynamicRoutingDataSource().addDataSource(dsName, dataSource);
    }

    /** 删除数据源 */
    public static void delDataSource(String dsName){
        dynamicRoutingDataSource().removeDataSource(dsName);
    }

    public static DynamicRoutingDataSource dynamicRoutingDataSource(){
        return SpringContextHolder.getBean(DynamicRoutingDataSource.class);
    }
}
